<template>
  <view>
    <view :style="{paddingBottom: safeBottom + 'px'}">
      <view :style="{height: height + 'px'}"></view>
      <TnNavbar fixed alpha customBack :placeholder="false" bg-color="transparent" :bottom-shadow="false">
        <view slot="back" class='tn-custom-nav-bar__back'>
          <text class='icon tn-icon-left'></text>
          <text class='icon tn-icon-home-capsule-fill'></text>
        </view>
        <text class="text-white"></text>
      </TnNavbar>
      <!-- 页面内容 -->
      <view class="bg-contaniner">
      </view>
      <view class="cu-draw-con flex flex-direction align-center">
        <view class="padding-bottom-sm neon-text">幸运转转转</view>
        <view class="cu-draw-box">
          <view class="cu-draw-b_box">
            <view class="flex align-center j_b cu-draw-prize_box">
              <block v-for="(item, index) in prize_list" :key="index">
                <!-- 抽奖 按钮 -->
                <block v-if="index == 4">
                  <view class="cu-draw-prize_start cu-draw-prize_item margin-lr-xs solids radius lg">
                    <view class="flex justify-center padding-sm padding-lr align-center" @tap="lottery">
                      <view class="flex align-center text-xxl text-white">开 始 抽 奖</view>
                    </view>
                  </view>
                </block>

                <!-- 奖项 -->
                <view
                    :class="'cu-draw-prize_item flex flex-direction align-center justify-center margin-lr-xs solids radius lg ' +
                  (item.active ?
                  'cu-draw-active' : '')">
                  <view class="cu-draw-prize_img">
                    <image class="radius lg" :src="item.image_url" mode="aspectFill"/>
                  </view>
                  <text class="text-white">{{ item.name }}</text>
                </view>
              </block>
            </view>
          </view>
        </view>
        <view class="text-white">
          您还有
          <text class="text-blue">{{ remian_num }}次</text>
          抽奖机会
        </view>
        <scroll-view style="height: 30vh" scroll-y class="margin">
          <view class="radius lg">
            <view v-html="content"></view>
<!--            <view class="text-black">说明：</view>
            <view class="text-black padding-top-xs">①点击开始抽奖按钮，等待滚动停止，将会弹出抽奖结果。</view>
            <view class="text-black padding-top-xs">
              ②礼包使用方式：进入游戏资料室-神奇密码解析仪-输入兑换码即可获得，或者h5右上角设置输入兑换码。
            </view>
            <view class="text-black padding-top-xs">③兑换码有效期截止至：
              <text class="text-green">2024年10月31日</text>
              (使用渠道：
              <text class="text-green">
                仅限大陆版赛尔号页游兑换
              </text>
              )。礼包码来自《好游快爆》，领取过同样奖励的账号可能无法重复领取。
            </view>
            <view class="padding-top-xs text-red">④每看一次广告可获取两次抽奖机会，离开本页面后，会重置抽奖次数，望各位大佬注意。
            </view>-->
          </view>
        </scroll-view>
      </view>
    </view>
    <TnPopup v-model="showPopup" width="80%" :overlay-closeable="false">
      <view class="padding-sm">
        <view class="padding-sm">
          恭喜您~中奖啦~
        </view>
        <view class="flex">
          <image :src="current.image_url" style="width: 80px;height: 80px" mode="widthFix"></image>
          <view class="flex flex-direction justify-between padding-tb">
            <text>{{ current.name }}*{{ current.num }}</text>
            <view>
              <text class="margin-right-sm">
                {{ current.code }}
              </text>
            </view>
          </view>
        </view>
        <view class="text-red padding-top-xs">
          中奖后请复制兑换码及时使用，中奖弹窗关闭后会刷新奖池，未复制兑换码的奖品会重新进入奖池，已复制的兑换码会被移出奖池。
        </view>
        <view class="flex flex-direction margin-top">
          <button @click="copyCode" class="cu-btn" style="background-color: #e95c74;color: #fff">领取并复制兑换码</button>
        </view>
      </view>
    </TnPopup>
  </view>
</template>

<script setup>
  import {ref, getCurrentInstance, onMounted} from 'vue'
  import TnNavbar from "../../uni_modules/tuniaoui-vue3/components/navbar/src/navbar.vue";
  import {useUniAppSystemRectInfo} from "@/uni_modules/tuniaoui-vue3/hooks/use-uniapp-system-rect-info";
  import TnPopup from '@/uni_modules/tuniaoui-vue3/components/popup/src/popup.vue'
  import {onShareAppMessage} from '@dcloudio/uni-app'
  import {getShowMessage, setShowMessage} from "../../storage/show_message";

  onShareAppMessage(() => {
    return {
      title: '赛迷小助手',
      imageUrl: 'https://seerforwdw.info/seer-image/diduo.jpg',
      path: '/pages/gift/gift'
    }
  })

  // 在页面中定义激励视频广告
  let videoAd = null

  // 在页面onLoad回调事件中创建激励视频广告实例
  if (wx.createRewardedVideoAd) {
    videoAd = wx.createRewardedVideoAd({
      adUnitId: 'adunit-ed8e7550fc631f1a'
    })
    videoAd.onLoad(() => {
    })
    videoAd.onError((err) => {
      console.error('激励视频光告加载失败', err)
    })
    videoAd.onClose((res) => {
      if (res.isEnded) {
        remian_num.value = remian_num.value + 2
        uni.showToast({
          title: '抽奖次数+2',
          icon: 'none'
        })
      }
    })
  }

  const {height} = useUniAppSystemRectInfo().navBarInfo
  const safeBottom = ref(0)

  const {
    proxy
  } = getCurrentInstance()

  const prize_list = ref([])

  const getList = async () => {
    prize_list.value = await proxy.$api.getGiftList({
      is_enabled: 1,
      limit: 8
    })
    let length = prize_list.value.length
    for (let i = 0; i < (8 - length); i++) {
      prize_list.value.push({
        image_url: 'https://image.meiye.art/Fha6tqRTIwHtlLW3xuZBJj8ZXSX3?imageMogr2/thumbnail/450x/interlace/1',
        name: '谢谢参与',
        active: false
      })
    }

    // 打乱数组
    for (let i = prize_list.value.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [prize_list.value[i], prize_list.value[j]] = [prize_list.value[j], prize_list.value[i]]; // 交换元素
    }

    prize_list.value.forEach(item => {
      item.active = false
    })

  }

  const remian_num = ref(0)
  //防止重复点击
  const lock = ref(false)


  //抽奖顺序的索引
  const prizeListIndex = ref([0, 1, 2, 4, 7, 6, 5, 3])

  // 抽奖动画
  const Timer = ref(null)

  const LotteryEnd = ref(false)

  //抽奖结束
  const nowRunIndex = ref(0)

  const current = ref({})
  const showPopup = ref(false)

  const lottery = () => {
    if (lock.value) return
    if (remian_num.value === 0) {
      uni.showModal({
        title: '提示',
        content: '抽奖次数不足了哦~要获取抽奖次数吗?',
        confirmText: '看广告',
        cancelText: '拉倒吧',
        success: res => {
          if (res.confirm) {
            if (videoAd) {
              videoAd.show().catch(() => {
                // 失败重试
                videoAd.load()
                    .then(() => videoAd.show())
                    .catch(err => {
                      console.error('激励视频 广告显示失败', err)
                    })
              })
            }
          }
        }
      })
      return
    }
    lock.value = true
    luckChose(randomRange(0, 7)).then((e) => {
      current.value = e[0]
      remian_num.value--
      if (current.value.id) {
        showPopup.value = true
      } else {
        uni.showToast({
          title: '感谢参与, 下次加油~',
          icon: 'none'
        })
      }
    });
  }

  // 范围随机数
  const randomRange = (lower, upper) => {
    return Math.floor(Math.random() * (upper - lower)) + lower;
  }

  //ative样式的索引，
  const luckChose = (luckIndex) => {
    return new Promise((resolve, reject) => {
      // console.log("中奖索引>>>", luckIndex)
      let maxTime = randomRange(2500, 4000); //抽奖的时间2.5s-4s之间
      // console.log(maxTime)
      let rI = 0.01;
      // console.log(this.nowRunIndex)
      if (nowRunIndex.value == 0) {
        //初始化从索引0开始显示抽奖激活的边框
        prize_list.value[0].active = true
      }

      function runAni(_t) {
        Timer.value = setTimeout(() => {
          let list = prize_list.value;
          ++nowRunIndex.value;
          // console.log(that.nowRunIndex >= that.data.prizeListIndex.length)
          // console.log(that.nowRunIndex)
          if (nowRunIndex.value >= prizeListIndex.value.length) {
            nowRunIndex.value = 0;
          } else {
            ('');
          }
          let Pindex = prizeListIndex.value[nowRunIndex.value];
          list.map((item, index) => {
            item.active = Pindex === index;
          });
          prize_list.value = list
          // console.log(that.LotteryEnd)
          // console.log(luckIndex == that.nowRunIndex)
          if (LotteryEnd.value && luckIndex == nowRunIndex.value) {
            clearTimeout(Timer.value);
            LotteryEnd.value = false;
            lock.value = false
            resolve(
                list.filter((v) => {
                  return v.active;
                })
            );
          } else {
            rI += 0.5;
            runAni(_t + rI);
          }
        }, _t);
      }

      runAni(80);
      setTimeout(() => {
        LotteryEnd.value = true;
      }, maxTime);
    });
  }

  // 领取兑换码
  const copyCode = async () => {
    try {
      showPopup.value = false
      const gift = await proxy.$api.getGiftList({
        id: current.value.id
      })
      if(gift && gift[0].is_enabled === 2) {
        uni.showModal({
          title: '提示',
          content: '手速太慢, 已经被其它小伙伴抢走啦~ 小伙子单身的还是不够久啊!',
          success: res => {
            if(res.confirm) {
              getList()
            }
          }
        })
      }else {
        await proxy.$api.updateGiftStatus({
          id: current.value.id,
          is_enabled: 2
        })
        uni.setClipboardData({
          data: current.value.code,
          showToast: false,
          success: () => {
            uni.showModal({
              title: '提示',
              content: '兑换码已复制, 请及时使用!',
              showCancel: false,
              success: res => {
                if (res.confirm) {
                  getList()
                }
              }
            })
          }
        })
      }
    } catch (e) {
      uni.showToast({
        title: e
      })
    }
  }

  const content = ref('')
  const handleGetGlobalConfigList = async () => {
    const data = await proxy.$api.getGlobalConfigList({
      key: ['gift-des']
    })
    content.value = data[0].content
  }

  onMounted(() => {
    handleGetGlobalConfigList()
    getList()
  })
</script>


<style scoped lang="scss">
  /* 移动背景部分 */
  .bg-contaniner {
    position: fixed;
    top: -0rpx;
    left: -300rpx;
    --text-color: hsl(0 95% 60%);
    --bg-color: hsl(0 0% 100%);
    --bg-size: 200px;
    height: 100%;
    display: grid;
    place-items: center;
    place-content: center;
    /* grid-template-areas: "body"; */
    overflow: hidden;
    font-family: "Dela Gothic One", sans-serif;
    background-color: var(--bg-color);
    z-index: -1;
  }

  .bg-contaniner::before {
    --size: 150vmax;

    grid-area: body;
    content: "";
    inline-size: var(--size);
    block-size: var(--size);
    background-image: url("https://resource.tuniaokj.com/images/animate/animate1.jpg");
    background-size: var(--bg-size);
    background-repeat: repeat;
    transform: rotate(45deg);
    opacity: 0.25;
    animation: bg 6s linear infinite;
  }

  @media (prefers-reduced-motion: reduce) {
    .bg-contaniner::before {
      animation-duration: 0s;
    }
  }

  @keyframes bg {
    to {
      background-position: 0 calc(var(--bg-size) * -1);
    }
  }

  .three-d-text {
    font-size: 30px;
    font-weight: bold;
    color: #e74c3c;
    text-shadow: 4px 4px 0 #2c3e50;
  }

  .neon-text {
    font-size: 30px;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 0 5px #f39dac, 0 0 10px #f39dac, 0 0 20px #f39dac, 0 0 40px #f39dac;
  }
</style>
